package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsMode;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Author: Farewell
 * @Date: 2022/5/25 19:50
 * @Description:
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public void productStatusUp(List<SkuEsMode> skuEsModes) {
        // 保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsMode skuEsMode : skuEsModes) {
            IndexRequest indexRequest = new IndexRequest();
            // 指定索引
            indexRequest.index(EsConstant.PRODUCT_INDEX);
            // 设置id
            indexRequest.id(skuEsMode.getSkuId().toString());
            // 添加数据
            // 转成json
            String json = JSON.toJSONString(skuEsMode);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 上传
        try {
            BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            BulkItemResponse[] items = bulk.getItems();
        } catch (IOException e) {
            log.error("批量上架商品失败");
        }

    }
}
